package com.ivan.toolkit.swing;

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

import javax.swing.JPanel;

public class GradientPanel extends JPanel {
	
	private static final long serialVersionUID = 1L;
	
	public static final int GradientHorizontal = 0;
	public static final int GradientVertical = 1;
	
	private Color background2 = null;  
	private int type = 0;
	
	private boolean reverseColors = false;


	public GradientPanel() {
	}

	public GradientPanel(Color firstColor, Color lastColor,	int type) {
		super();
		this.setBackground(firstColor);
		this.setBackground2(lastColor);
		this.type = type;
		update();
	}

	void update() {
		this.invalidate();
		this.repaint();
	}

	public Color getBackground2() {
		return background2;
	}

	public void setBackground2(Color background2) {
		this.background2 = background2;
		update();
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
		update();
	}
	
	

	public boolean isReverseColors() {
		return reverseColors;
	}

	public void setReverseColors(boolean reverseColors) {
		this.reverseColors = reverseColors;
	}

	@Override
	protected void paintComponent(Graphics g) {
		
		Color color1 = this.getBackground();
		Color color2 = this.getBackground2();
		
		if(color2 == null) {
			
			super.paintComponent(g);
			
		} else {
			
			float w = (float)this.getSize().getWidth();
			float h = (float)this.getSize().getHeight();
			
			Graphics2D g2D = (Graphics2D) g;
			Point2D.Float p1 = null;
			Point2D.Float p2 = null;
			
			if(type == GradientHorizontal) {
			
				p1 = new Point2D.Float(0.f, 0.f);
				p2 = new Point2D.Float(w, 0.f);
				
			} else {
				
				p1 = new Point2D.Float(0.f, 0.f);
				p2 = new Point2D.Float(0.f, h);
				
			}
			
			if(this.reverseColors) {
				Point2D.Float temp = p1;
				p1 = p2;
				p2 = temp;
			}
						
			GradientPaint g1 = new GradientPaint(p1, color1, p2, color2, false);
			
			Rectangle2D.Float rect1 = new Rectangle2D.Float(0.f, 0.f, w, h);
			g2D.setPaint(g1);
			g2D.fill(rect1);
		}
	}
	
	

}
